package com.cfcoding.network;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author tristan
 */
public class IPValidator {

    private Pattern v4pattern, v6pattern;
    private String IP4_PATTERN =
            "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
    private String IP6_PATTERN = 
            "\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|"
           +"(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]"
           +"|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d"
           +"|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9"
           +"A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]"
           +"?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|("
           +"([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|("
           +"(:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]"
           +"?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|"
           +"(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|"
           +"((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|"
           +"[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))"
           +"|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1"
           +",5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1"
           +"\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))"
           +"{3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,"
           +"4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4"
           +"]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]"
           +"?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-"
           +"9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?"
           +"\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))("
           +"%.+)?\\s*";

    public IPValidator() {
        v4pattern = Pattern.compile(IP4_PATTERN);
        v6pattern = Pattern.compile(IP6_PATTERN);
    }
    
    public boolean isIPv4(String ip) {
       Matcher matcher = v4pattern.matcher(ip);
        return matcher.matches();
    }
    
    public boolean isIPv6(String ip) {
        Matcher matcher = v6pattern.matcher(ip);
        return matcher.matches();
    }
    
    public String matchIPv4 (String s) {
        Matcher matcher = v4pattern.matcher(s);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }
    
    public String matchIPv6 (String s) {
        Matcher matcher = v6pattern.matcher(s);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }
}